/**
 * COPYRIGHT HangZhou Trustway Technology Company Limited
 * All right reserved.
 */
package com.robam.cloud.restful.config.repeatlimit.aop;

import com.robam.cloud.cache.util.RedisLock;
import com.robam.cloud.common.bean.restful.entity.RespMsg;
import com.robam.cloud.restful.config.repeatlimit.annotation.NoRepeatSubmit;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * @Description
 * @Author 薛铁琪
 * @CreateTime 2019-06-20 16:01
 * @Version 1.0
 */
@Aspect
@Component
@Slf4j
public class RepeatSubmitAspect {

    @Autowired
    private RedisLock redisLock;

    @Pointcut("@annotation(noRepeatSubmit)")
    public void pointCut(NoRepeatSubmit noRepeatSubmit) {
    }

    @Around("pointCut(noRepeatSubmit)")
    public Object around(ProceedingJoinPoint pjp, NoRepeatSubmit noRepeatSubmit) throws Throwable {

        //Object result = null;
        //得到被切面修饰的方法的参数列表
        Object[] args = pjp.getArgs();
        // 得到被代理的方法
        Method method = ((MethodSignature) pjp.getSignature()).getMethod();
        String key = noRepeatSubmit.key();
        String realkey = parseKey(key, method, args);
        int lockSeconds = noRepeatSubmit.lockTime();

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Assert.notNull(request, "request can not null");
        String clientId = getClientId();

        boolean isSuccess = redisLock.lock(realkey, clientId, lockSeconds);
        log.debug("tryLock key = [{}], clientId = [{}]", key, clientId);

        if (isSuccess) {
            log.debug("tryLock success, key = [{}], clientId = [{}]", key, clientId);
            // 获取锁成功
            Object result;

            try {
                // 执行进程
                result = pjp.proceed();
            } finally {
                // 解锁
                if (!noRepeatSubmit.isMust()) {
                    redisLock.unlock(realkey, clientId);
                    log.debug("releaseLock success, key = [{}], clientId = [{}]", key, clientId);
                }
            }

            return result;

        } else {
            // 获取锁失败，认为是重复提交的请求
            log.debug("tryLock fail, key = [{}]", key);
            return RespMsg.error(500, "操作频繁，请稍后再试(LimitRepeatSubmit)");
        }

    }

    private String getClientId() {
        return UUID.randomUUID().toString();
    }


    /**
     * 获取缓存的key
     * key 定义在注解上，支持SPEL表达式
     *
     * @return
     */
    private String parseKey(String key, Method method, Object[] args) {

        if (StringUtils.isEmpty((key))) {
            return null;
        }

        //获取被拦截方法参数名列表(使用Spring支持类库)
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paraNameArr = u.getParameterNames(method);

        //使用SPEL进行key的解析
        ExpressionParser parser = new SpelExpressionParser();
        //SPEL上下文
        StandardEvaluationContext context = new StandardEvaluationContext();
        //把方法参数放入SPEL上下文中
        for (int i = 0; i < paraNameArr.length; i++) {
            context.setVariable(paraNameArr[i], args[i]);
        }
        return parser.parseExpression(key).getValue(context, String.class);
    }

}